/*
 * @Description:
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-06-02 15:12:35
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2024-06-18 17:30:16
 */
import type { MqttClient, OnMessageCallback } from 'mqtt'
import * as mqtt from 'mqtt/dist/mqtt.min.js'

const hostConfig = {
	'180.101.239.5': {
		ws: 'ws://180.101.239.5:57575/mqtt',
		username: 'admin',
		password: 'apld_public',
	},
	'mzj.nanjing.gov.cn': {
		ws: 'ws://180.101.239.5:57575/mqtt',
		username: 'admin',
		password: 'apld_public',
	},
	base: {
		ws: 'ws://116.62.40.103:8083/mqtt',
		username: 'emqx',
		password: 'public',
	},
}

const baseConfig = hostConfig[window.location.hostname] || hostConfig['base']
const MQTT_SERVICE_SSL = 'wss://emqx.njapld.com:8084/mqtt'
const MQTT_SERVICE = baseConfig.ws
const isSSL = 'https:' == window.location.protocol ? true : false

let topicList = []
class MQTT {
	url: string
	topic: string
	hostname?: string // 对主题需要区分环境的时候使用
	client!: MqttClient
	constructor(topic?: string) {
		this.hostname = import.meta.env.MODE == 'development' ? '192.168.0.124:8086' : window.location.host
		if (window.location.host == 'mzj.nanjing.gov.cn') {
			this.hostname = '180.101.239.5:11762'
		}
		this.topic = `${this.hostname}/${topic}`
		this.url = isSSL ? MQTT_SERVICE_SSL : MQTT_SERVICE
	}

	init() {
		const options = {
			clientId: 'ningxiang_' + Math.random().toString(16).substring(2, 8),
			connectTimeout: 4000, // 超时时间
			reconnectPeriod: 4000, // 重连时间间隔
			username: 'emqx',
			password: 'public',
			clean: false, // 保留会话
		}
		this.client = mqtt.connect(this.url, options)
		this.client.on('error', (err) => {
			console.log(err, '连接失败')
		})
		this.client.on('reconnect', (e) => {
			console.log(e, 'reconnect---------')
		})
	}

	//连接
	link(topic?: string) {
		if (topic) {
			this.topic = `${this.hostname}/${topic}`
		}
		this.client.on('connect', () => {
			if (!topicList.includes(topic)) {
				this.doSubscribe()
			}
		})
	}
	//收到的消息
	get(callback: OnMessageCallback) {
		this.client.on('message', callback)
	}
	// 开始订阅
	doSubscribe() {
		this.client.subscribe(this.topic, { qos: 2 }, (error, res) => {
			if (error) {
				console.log('订阅主题失败', error)
				return
			}
			topicList.push(this.topic)
			console.log('订阅成功--', this.topic, res)
		})
	}
	// 取消订阅
	doUnSubscribe() {
		this.client.unsubscribe(this.topic, (error) => {
			if (error) {
				console.log('取消订阅失败', error)
			}else {
        console.log('取消订阅')
      }
		})
	}
	doPublish(topic, payload) {
		const publish_topic = `${this.hostname}/${topic}`
		this.client.publish(publish_topic, payload, { qos: 2 }, (error) => {
			console.log(publish_topic, '发布成功')
			if (error) {
				console.log('消息发布失败', error)
			}
		})
	}
	destroyConnection() {
		if (this.client.connected) {
			try {
				this.client.end(false, () => {
					console.log('Successfully disconnected!')
				})
			} catch (error) {
				console.log('Disconnect failed', error.toString())
			}
		}
	}
}
export default MQTT
